﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;

namespace WeightControl
{
    public partial class Form1 : Form
    {
        private bool IsRun = true;
        Thread TaskWork;
        private string mType = string.Empty;
        ConcurrentStack<List<string>> MsgStack = new ConcurrentStack<List<string>>();
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //TaskWork = new Thread(new ThreadStart(StartWork));
            //TaskWork.Start();

        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            IsRun = false;
           
        }

        /// <summary>
        /// 选择仪表类型
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmbType_SelectedIndexChanged(object sender, EventArgs e)
        {
            mType = cmbType.Text.Trim();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                string portStr = cmbPort.Text.Trim();
                string budratestr = cmbBudrate.Text.Trim();
                int port = 0, budrate = 0;
                bool b = int.TryParse(portStr, out port);
                if (!b)
                {
                    MessageBox.Show("请选择串口号!");
                    return;
                }

                bool b1 = int.TryParse(budratestr, out budrate);
                if (!b1)
                {
                    MessageBox.Show("请选择波特率!");
                    return;
                }

             

                serialPort1.PortName = "COM" + port;
                serialPort1.BaudRate = budrate;
                serialPort1.Open();
                if(serialPort1.IsOpen)
                {
                    MessageBox.Show("打开串口成功!");
                }
                else
                {
                    MessageBox.Show("打开串口失败!");
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show("打开串口失败,"+ex.Message+ex.StackTrace);
            }
        
            
        }


        private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            int count = serialPort1.BytesToRead;//byte方式读          
                                              //接收到的str数据中有中文，编码成GB2312，可正常显示中文      
            byte[] bytes = new byte[count];
            serialPort1.Read(bytes, 0, count);
            string str1 = System.Text.Encoding.Default.GetString(bytes);
            handMsg(str1);
            ShowInfo(str1);
        }

        StringBuilder logBuider = new StringBuilder();
        private void ShowInfo(string msg)
        {
            logBuider.Append(msg);
            if(logBuider.Length >200)
            {
                msg = logBuider.ToString();
                logBuider.Clear();
                if (textBox1.InvokeRequired)
                {
                    textBox1.Invoke(new Action<string>(ShowInfo), new object[] { msg });
                }
                else
                {
                    textBox1.AppendText(msg);
                }
            }
        }

        private void handMsg(string msg)
        {
            if (mType == "托利多Ind880")
            {
                TuoLiDuoIn880(msg);
            }
            else if(mType == "耀华A9")
            {
                YaoHaA9(msg);
            }
            else if(mType == "D2008")
            {
                D2008(msg);
            }
        }

        #region 仪表数据解析


        /// <summary>
        /// 耀华A9
        /// </summary>
        /// <param name="msg"></param>
        private void YaoHaA9(string msg)
        {
            if(!string.IsNullOrEmpty(msg))
            {
                int pot = msg.IndexOf("\u0002");
                int start = pot + "\u0002".Length;
                int end = msg.LastIndexOf("\u0003");
                int len = end - start;
                if(len > 0)
                {
                    msg = msg.Substring(start, len);
                    string[] arr = msg.Split(new char[] { '\u0002', '\u0003' });
                    List<string> list = new List<string>();
                    int weight = 0;
                    foreach(string item in arr)
                    {
                        if (string.IsNullOrEmpty(item)) continue;
                        if(item.StartsWith("+") || item.StartsWith("-") )
                        {
                            string Nav = item.Substring(0, 1);
                            if(item.Length >=8)
                            {
                                string val = item.Substring(1, 7);
                                if(Nav=="-")
                                {
                                   bool b =  int.TryParse(val, out weight);
                                    if(b)
                                    {
                                        list.Add(Convert.ToString (weight*-1));
                                    }
                                }
                                else
                                {
                                    bool b = int.TryParse(val, out weight);
                                    if (b)
                                    {
                                        list.Add(Convert.ToString(weight));
                                    }

                                }
                            }
                            
                        }
                    }
                    SetData(list);

                }
            }
        }

        string TuoLiDuoMsg = string.Empty;
        /// <summary>
        /// 托利多Ind880
        /// </summary>
        /// <param name="msg"></param>
        private void TuoLiDuoIn880(string val)
        {
            TuoLiDuoMsg = TuoLiDuoMsg + val;
            string msg = string.Empty;
            if (TuoLiDuoMsg.Length > 30)
            {
                msg = TuoLiDuoMsg;
                TuoLiDuoMsg = string.Empty;
            }
            else
            {
                return;
            }
            int start = msg.IndexOf("\u0002");
            if(start >= 0)
            {
                int end = msg.LastIndexOf("00\r");
                int len = end - start + "00\r".Length;
                if (len < 0 || start + len > msg.Length)
                {
                    ShowInfo("截取错误");
                    return;
                }
                msg = msg.Substring(start, len);
            }
            else
            {
                ShowInfo("内容错误");
                return;
            }
            msg = msg.Replace("\u000218",",");
            msg = msg.Replace("\u000210",",");
            msg = msg.Replace("00\r", ",");
            string[] arr = msg.Split(new char[] { ','},StringSplitOptions.RemoveEmptyEntries);
            string tmp = string.Empty;
            List<string> list = new List<string>();
            foreach(string item  in arr)
            {
                if(tmp != item)
                {
                    if (item.Contains("$LHHH&&$$$$&")) continue;
                    if (item.Length == 0) continue;
                    list.Add(item);
                 
                    tmp = item;
                }
            }
            SetData(list);
            
        }


        public string S2008Msg { get; set; }
        private void D2008(string val)
        {
            S2008Msg = S2008Msg + val;
            string msg = string.Empty;
            if (S2008Msg.Length > 30)
            {
                msg = S2008Msg;
                S2008Msg = string.Empty;
            }
            else
            {
                return;
            }
            int start = msg.IndexOf("\u0002");
            if (start >= 0)
            {
                int end = msg.LastIndexOf("\u0003");
                int len = end - start + "\u0003".Length;
                if (len < 0 || start + len > msg.Length)
                {
                    ShowInfo("截取错误");
                    return;
                }
                msg = msg.Substring(start, len);
            }
            else
            {
                ShowInfo("内容错误");
                return;
            }
            msg = msg.Replace("\u0002", ",");
            msg = msg.Replace("\u0003", ",");
            string[] arr = msg.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            string tmp = string.Empty;
            List<string> list = new List<string>();
            string flag = string.Empty;
            string tmpVal = string.Empty;
            foreach (string item in arr)
            {
                if (tmp != item)
                {
                    if (item.Length == 0) continue;
                    if (item.Length != 10) continue;
                    flag =  item.Substring(0,1);
                    tmpVal = item.Substring(1,6);
                    if(flag !="+")
                    {
                        tmpVal = flag + tmpVal;
                    }
                    list.Add(tmpVal);

                    tmp = item;
                }
            }
            SetData(list);
        }
        #endregion 仪表数据解析


        #region 显示数据到UI 
        private void SetData(List<string> list )
        {
            if (list == null || list.Count == 0) return;
            if(button1.InvokeRequired)
            {
                button1.Invoke(new Action<List<string>>(SetData),new object[] { list });

            }
            else
            {
                foreach (string item in list)
                {
                    double val = 0;
                    bool b = double.TryParse(item, out val);
                    if (b)
                    {
                        button1.Text = Convert.ToString(val);
                    }
                }
            }
        }

        private void  SetDataToUi(List<string> vals)
        {
            if(button1.InvokeRequired)
            {
                button1.Invoke(new Action<List<string>>(SetDataToUi),new object[] { vals });
            }
            else
            {
                foreach(string item in vals)
                {
                    double val = 0;
                   bool b =  double.TryParse(item,out val);
                    if(b)
                    {
                        button1.Text = Convert.ToString( val);
                    }
                }
               
            }
        }


        #endregion 显示数据到UI

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            IsRun = false;
            serialPort1.Close();
        }


        private void StartWork()
        {
           while(IsRun)
            {
                try
                {
                    List<string> list = new List<string>();
                    MsgStack.TryPop(out list);
                    if(list != null && list.Count > 0)
                    {
                        SetData(list);
                        MsgStack.Clear();
                    }
                   
                }
                catch(Exception ex)
                {

                }
                finally
                {
                    Thread.Sleep(100);
                }
            }
        }
    }
}
